package com.yc.sole.framework.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author yizuomin
 * @date 2023/3/9 18:03
 **/
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(ThreadConfigProperties.class)
public class ThreadConfig {

    private final ThreadConfigProperties properties;

    /**
     * 基础线程池
     *
     * @return
     */
    @Primary
    @Bean(name = "async_thread_pool")
    public ThreadPoolTaskExecutor asyncThreadPool() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //线程前缀
        threadPoolTaskExecutor.setThreadNamePrefix(properties.getThreadNamePrefix());
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(properties.getCorePoolSize());
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(properties.getMaxPoolSize());
        //是否允许核心线程超时
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(properties.getAllowCoreThreadTimeOut());
        //线程存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        //线程队列大小
        threadPoolTaskExecutor.setQueueCapacity(properties.getQueueCapacity());
        //拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }

    /**
     * netty线程池
     *
     * @return
     */
    @Bean(name = "netty_thread_pool")
    public ThreadPoolTaskExecutor nettyThreadPool() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //线程前缀
        threadPoolTaskExecutor.setThreadNamePrefix("netty-task-");
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(properties.getCorePoolSize());
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(properties.getMaxPoolSize());
        //是否允许核心线程超时
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(properties.getAllowCoreThreadTimeOut());
        //线程存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        //线程队列大小
        threadPoolTaskExecutor.setQueueCapacity(properties.getQueueCapacity());
        //拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
}
